package com.mes.designer;

import com.mes.data.EmesPBom;
import com.mes.data.EmesProcessRoute;
import org.hibernate.Query;
import org.openbravo.base.exception.OBException;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.service.db.DalConnectionProvider;
import java.util.Date;
import java.util.List;

public class EmesRouteDesigner {
	/**
	 * 根据单一的工艺路线
	 * 
	 * @param productId
	 * @param date
	 * @return
	 */
	public EmesProcessRoute GetActiveRouteID(String productId, Date date) {
		if (productId == null || "".equalsIgnoreCase(productId.trim())) {
			String language = OBContext.getOBContext().getLanguage().getLanguage();
			ConnectionProvider conn = new DalConnectionProvider(false);
			throw new OBException(Utility.messageBD(conn, "您必须指定一个工艺流程以供查询。请仔细检查。", language));
		}
		
		String hql = "select epr from " + EmesProcessRoute.ENTITY_NAME + " epr where epr.product.id=:productId and epr.default = :isDefault " +
				"and :date >=epr.activityDateFrom and :date <=epr.activityDateTo";
		if (date != null) {
			date = new Date();
		}
		
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("productId", productId);
		query.setBoolean("isDefault", true);
		query.setTime("date", date);
		List<EmesProcessRoute> list = query.list();
		
		if (list.isEmpty()) {
			return null;
		} else {
			return list.get(0);
		}
	}
	
	public EmesPBom GetActiveBOMID(String productId, Date date) {
		if (productId == null || "".equalsIgnoreCase(productId.trim())) {
			String language = OBContext.getOBContext().getLanguage().getLanguage();
			ConnectionProvider conn = new DalConnectionProvider(false);
			throw new OBException(Utility.messageBD(conn, "您必须指定一个产品ID以供查询。请仔细检查。", language));
		}
		
		String hql = "select ep from " + EmesPBom.ENTITY_NAME + " ep where ep.product.id=:productId and ep.default = :isDefault " +
				"and :date >=ep.activityDateFrom and :date <=ep.activityDateTo";
		if (date == null) {
			date = new Date();
		}
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("productId", productId);
		query.setTime("date", date);
		query.setBoolean("isDefault", true);
		List<EmesPBom> list = query.list();
		
		if (list.isEmpty()) {
			return null;
		} else {
			return list.get(0);
		}
	}
}
